package com.zhyl.demo.controller;


import com.zhyl.demo.entity.Appointment;
import com.zhyl.demo.entity.Doctor;
import com.zhyl.demo.entity.Patient;

import com.zhyl.demo.entity.User;
import com.zhyl.demo.service.*;
import com.zhyl.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yang3
 */
@RestController
@RequestMapping("/appointment")
public class AppointmentController {

    private final AppointmentService appointmentService;
    private final PatientService patientService;
    private final DoctorService doctorService;
    private final TheEndService theEndService;
    private final UserService userService;

    @Autowired
    private AppointmentController(AppointmentService appointmentService,
                                  PatientService patientService,
                                  DoctorService doctorService,
                                  TheEndService theEndService,
                                  UserService userService) {
        this.appointmentService = appointmentService;
        this.patientService = patientService;
        this.doctorService = doctorService;
        this.theEndService = theEndService;
        this.userService = userService;
    }

    /**
     * 获取预约列表
     *
     * @param patid
     * @return
     */
    @RequestMapping("/loadAppointments")
    public Result loadAppointments(Integer patid) {
        ArrayList<Appointment> appointment;
        appointment = appointmentService.loadAppointments(patid);

        if (appointment != null) {
            int i = 0;
            for (Appointment item :
                    appointment) {
                item.setPatient(patientService.showInfo(appointment.get(i).getPatientId()));
                item.setDoctor(doctorService.docInfo(appointment.get(i).getDoctorId()));
                i++;
            }
            return Result.success(appointment);
        } else {
            return Result.error("暂无预约信息");
        }

    }

    @RequestMapping("/selectByDoc")
    public Result selectByDoc(int docId) {
        if (docId <= 0) {
            return Result.error("-1", "参数错误");
        }
        ArrayList<Appointment> appointments = appointmentService.selectByDoc(docId);
        for (Appointment item : appointments) {
            item.setPatient(patientService.showInfo(item.getPatientId()));
            item.setDoctor(doctorService.docInfo(item.getDoctorId()));
        }
        return Result.success(appointments);
    }

    /**
     * 创建新预约
     *
     * @param appointment
     * @return
     */
    @PostMapping("/newAppointment")
    public Result newAppointment(@RequestBody Appointment appointment) {
        if (appointment == null) {
            return Result.error("-1", "无数据提交");
        }
        Patient patient = patientService.showInfo(appointment.getPatientId());
        if (patient.getName()==null){
            return Result.error("-1","请先完善个人信息");
        }

        if (patient.getBalance()-appointment.getZhenduanfei()<0){
            return Result.error("-1","余额不足");
        }

       if (theEndService.checkHasPay(appointment.getPatientId()) != null) {
            if (theEndService.checkHasPay(appointment.getPatientId()) == -1) {
                return Result.error("-1", "参数错误");
            }

            if (theEndService.checkHasPay(appointment.getPatientId()) > 0) {
                return Result.error("-1", "有未支付的问诊单待处理");
            }
        }


        LocalTime time = LocalTime.parse(new SimpleDateFormat("HH:mm:ss").format(appointment.getAppointmentTime()), DateTimeFormatter.ofPattern("HH:mm:ss"));



        Doctor doctor = doctorService.docInfo(appointment.getDoctorId());
        if (doctor.getBeginTime().isAfter(time) || doctor.getEndTime().isBefore(time)) {
            return Result.error("-1", "预约时间不在医生值班时间内");
        }
        patient.setBalance(patient.getBalance()-appointment.getZhenduanfei());
        Boolean b = patientService.updateInfo(patient);
        if (b){
            Boolean isSuccess = appointmentService.newAppointment(appointment);
            if (isSuccess) {

            return Result.success();
            } else {
                patient.setBalance(patient.getBalance()+appointment.getZhenduanfei());
                patientService.updateInfo(patient);
            return Result.error("-1", "预约失败");
            }
        }else {
            return Result.error("-1", "余额不足");
        }
    }


    //得到admin用户


    @RequestMapping("/getNowDayAppointment")
    public Result getNowDayAppointment(int docId, String time) {
        if (docId <= 0 || time == "") {
            return Result.error("参数错误");
        }
        Integer nowDayAppointment = appointmentService.getNowDayAppointment(docId, time);
        if (nowDayAppointment != null) {
            return Result.success(nowDayAppointment);
        } else {
            return Result.error("获取失败");
        }
    }

    @RequestMapping("/getDocAppointment")
    public Result getDocAppointment(int docId) {
        ArrayList<Appointment> docAppointment = appointmentService.getDocAppointment(docId);
        if (docAppointment != null) {
            int i = 0;
            for (Appointment item :
                    docAppointment) {
                item.setPatient(patientService.showInfo(docAppointment.get(i).getPatientId()));
                item.setDoctor(doctorService.docInfo(docAppointment.get(i).getDoctorId()));
                if (item.getDoctor().getIsSpecialist() == 0) {
                    item.setZhenduanfei(50.0);
                } else if (item.getDoctor().getIsSpecialist() == 1) {
                    item.setZhenduanfei(100.0);
                }
                i++;
            }
            return Result.success(docAppointment);
        } else {
            return Result.error("暂无预约信息");
        }
    }

    @RequestMapping("getAppointmentDetail")
    private Result getAppointmentDetail(int id) {
        if (id < 0) {
            return Result.error("-1", "查无此人");
        }
        Appointment appointmentDetail = appointmentService.getAppointmentDetail(id);
        appointmentDetail.setDoctor(doctorService.docInfo(appointmentDetail.getDoctorId()));
        appointmentDetail.setPatient(patientService.showInfo(appointmentDetail.getPatientId()));
        return Result.success(appointmentDetail);
    }

    @PostMapping("/updateAppointmentDetail")
    public Result updateAppointmentDetail(@RequestBody Appointment appointment) {
        if (appointment != null) {
            Doctor doctor = doctorService.docInfo(appointment.getDoctorId());
            Date appointmentTime = appointment.getAppointmentTime();
            //转换为localtime
            LocalTime time = LocalTime.parse(new SimpleDateFormat("HH:mm:ss").format(appointmentTime), DateTimeFormatter.ofPattern("HH:mm:ss"));
            if (doctor.getBeginTime().isAfter(time) || doctor.getEndTime().isBefore(time)) {
                String msg = "预约时间不在医生值班时间内";
                return Result.error("-1", msg);
            } else {
                Integer integer = appointmentService.updateAppointmentDetail(appointment);
                if (integer == 1) {
                    return Result.success();
                } else {
                    return Result.error("-1", "修改失败");
                }
            }
        } else {
            return Result.error("-1", "无数据提交");
        }


    }

    @RequestMapping("/callPatient")
    public Result callPatient(int id) {
        if (id <= 0) {
            return Result.error("-1", "参数错误");
        }
        Boolean aBoolean = appointmentService.callPatient(id);
        if (aBoolean) {
            return Result.success();
        } else {
            return Result.error("-1", "未能叫号");
        }
    }

    @RequestMapping("/cancelCall")
    public Result cancelCall(int id) {
        if (id <= 0) {
            return Result.error("-1", "参数错误");
        }
        Boolean aBoolean = appointmentService.cancelCall(id);
        if (aBoolean) {
            return Result.success();
        } else {
            return Result.error("-1", "未能叫号");
        }
    }

    @RequestMapping("/checkCall")
    public Result checkCall(int docId) {
        if (docId <= 0) {
            return Result.error("-1", "参数错误");
        }
        Integer integer = appointmentService.checkCall(docId);
        return Result.success(integer);

    }

    @RequestMapping("/searchPatient")
    public Result searchPatient(String patientName, int docId) {
        if (patientName == null || docId <= 0) {
            return Result.error("-1", "参数错误");
        }
        ArrayList<Patient> patients = patientService.searchInfo(patientName);
        ArrayList<Appointment> searchList = new ArrayList<>();
        for (Patient item : patients) {
            ArrayList<Appointment> appointments = appointmentService.searchPatient(item.getPatid(), docId);
            for (Appointment appointment : appointments) {
                appointment.setPatient(patientService.showInfo(appointment.getPatientId()));
                appointment.setDoctor(doctorService.docInfo(appointment.getDoctorId()));
                searchList.add(appointment);
            }
        }

        return Result.success(searchList);

    }

    @RequestMapping("/cancelAppointment")
    public Result cancelAppointment(int appointmentId){

        if(appointmentId<=0){
            return Result.error("-1","参数错误");
        }
        Appointment appointmentDetail = appointmentService.getAppointmentDetail(appointmentId);
        boolean isBefore = isBeforeOneDay(appointmentDetail.getAppointmentTime());
        if (!isBefore) {
            long minutesDifference = getMinutesDifference(appointmentDetail.getAppointmentTime());
             if (minutesDifference < 30) {
                 return Result.error("-1", "预约时间截至时间小于半小时，无法取消");
             }
        }
        Double zhenduanfei = appointmentDetail.getZhenduanfei();
        Patient patient = patientService.showInfo(appointmentDetail.getPatientId());
        Boolean res = appointmentService.cancelAppointment(appointmentId);
        if(res){
            patient.setBalance(patient.getBalance()+zhenduanfei);
            Boolean b = patientService.addBalance(patient);
            if (b){
                return Result.success();
            }else {
                return Result.error("-1", "余额返还失败请联系客服");
            }
        }else{
            return Result.error("-1","取消失败");
        }
    }

    //判断时间是否超一天
    public static boolean isBeforeOneDay(Date reservationTime) {
        Date now = new Date();
        long diffInMillies =  reservationTime.getTime() - Math.abs(now.getTime());
        long oneDayInMillies = 24 * 60 * 60 * 1000;
        return diffInMillies >= oneDayInMillies;
    }
    //判断截至时间是否大于半小时
     public static long getMinutesDifference(Date reservationTime) {
        Date now = new Date();
        long diffInMillies = Math.abs(now.getTime() - reservationTime.getTime());
        return TimeUnit.MINUTES.convert(diffInMillies, TimeUnit.MILLISECONDS);
    }

    @RequestMapping("/deleteAppointment")
    public Result deleteAppointment(int appointmentId){

        if(appointmentId<=0){
            return Result.error("-1","参数错误");
        }
        Boolean res = appointmentService.deleteAppointment(appointmentId);
        if(res){
            return Result.success();
        }else{
            return Result.error("-1","删除失败");
        }
    }

    @RequestMapping("/completeAppointment")
    public Result completeAppointment(int appointmentId){

        if(appointmentId<=0){
            return Result.error("-1","参数错误");
        }

        Boolean res = appointmentService.completeAppointment(appointmentId);
        if(res){
            return Result.success();

        }else {
            return Result.error("-1","失败");
        }

    }

}
